/**
 *
 */
package kevin.study.zephyr.internal;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import kevin.study.zephyr.domain.model.Entity;
import kevin.study.zephyr.exceptions.EntityMissingException;

/**
 * @author Kevin.Huang
 * @date 2007-9-20
 */
public final class ItemManager {

	@SuppressWarnings("unchecked")
	private Map<String, Class< ? extends Entity >> entitys = new HashMap<String, Class< ? extends Entity >>();

	private ItemManager() {
		super();
	}

	static final class ItemManagerHolder {
		private ItemManagerHolder() {
		}

		static final ItemManager SINGLETON = new ItemManager();
	}

	/**
	 * 获取ItemManager实例
	 *
	 * @return
	 */
	public static ItemManager getDefault() {
		return ItemManagerHolder.SINGLETON;
	}

	/**
	 * 注册Entity
	 *
	 * @param entityClass
	 */
	@SuppressWarnings("unchecked")
	public void registerItemEntity(String key, Class< ? extends Entity > entityClass) {
		entitys.put(key, entityClass);
	}

	public Set<String> getEntityTypes() {
		return entitys.keySet();
	}

	/**
	 * 生成Entity实例
	 *
	 * @param key
	 * @return
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws EntityMissingException
	 */
	@SuppressWarnings("unchecked")
	public Entity createEntity(String key) throws InstantiationException, IllegalAccessException,
			EntityMissingException {
		Class< ? extends Entity > entityClass = entitys.get(key);
		if (entityClass != null) {
			return entityClass.newInstance();
		} else {
			EntityMissingException e = new EntityMissingException("Not in ItemManager,Please regiser it!");
			e.setKey(key);
			throw e;
		}
	}
}
